package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    //微信接口服务
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxLogIn(UserLoginDTO userLoginDTO) {
    //获取到授权码code和jwt令牌token后，就可以查询用户信息了
        String code = userLoginDTO.getCode();
        String openid = getOpenid(code);//这是根据code获取openid的方法，所以必须要code;技术就用HTTPClient
    //根据openid查询用户信息
        User user0=userMapper.wxLogIn(openid);
        if(user0==null){//没有查到就自动创建新用户
            user0=new User();
            user0.setOpenid(openid);
            user0.setCreateTime(LocalDateTime.now());
            userMapper.addUser(user0);
        }
        return user0;
    }

    private String getOpenid(String code) {
        //请求参数封装
        Map map=new HashMap();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        //调用工具类，向微信接口服务发送请求(重点）
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        log.info("微信登录返回结果,{}",json);

        //解析json字符串
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        log.info("微信用户的openid为：{}", openid);
        return openid;
    }

}
